package com.yy.myconfig;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author young
 * @date 2022/12/23 20:37
 * @description: 自定义一个轮询算法
 */
@Component
public class MyRandomRule implements LoadBalancer{
    private final AtomicInteger atomicInteger =new AtomicInteger(0);
    public final int getAndIncrement(){
        int current;
        int next;
        
        do {
            current=this.atomicInteger.get();
            next=current>=Integer.MAX_VALUE?0:current+1;
            //自旋锁设计
        }while (!this.atomicInteger.compareAndSet(current,next));
        System.out.println("访问次数为："+next+"次");
        return next;
    }
    //负载均衡算法: rest接口第几次请求数%服务器集群总数量=实际调用服务器位置下标m，每次服务重启动后rest接口
    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
       int index= getAndIncrement()%serviceInstances.size();
       return serviceInstances.get(index);
    }
}
